package com.rivulet.doj_backend.depend;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;

import java.util.Locale;
import java.util.stream.Collectors;

public abstract class ControllerSupport {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private MessageSource messageSource;
    @Autowired
    protected RestResponses restResponses;

    public ControllerSupport() {
    }

    protected void checkBindingResult(BindingResult result) {
        if (result.hasErrors()) {
            String errorMsg = (String)result.getAllErrors().stream().map(this::translateError).collect(Collectors.joining(","));
            throw new ServiceException(DefaultStatus.toStatus(CommonStatus.illegalArgument.getCode(), errorMsg));
        }
    }

    private String translateError(ObjectError error) {
        String prefix = "";
        if (error instanceof FieldError) {
            FieldError fieldError = (FieldError)error;
            prefix = fieldError.getField();
        }

        return "[" + prefix + this.messageSource.getMessage(error, (Locale)null) + "]";
    }
}